
/*
 * 1.创建socket
 * 2.绑定自己的IP信息和端口
 * 3.阻塞式接收数据包
 * 4.处理收到的数据
 */

#include "stdio.h"
#include "string.h"
#include "sys/socket.h"
#include "netinet/in.h"
#include "stdlib.h"
#include "arpa/inet.h"
#include "errno.h"

#define MAXBUF	128
#define	IP	INADDR_ANY
#define	PORT	7838

int main(int argc, char **argv)
{
	struct sockaddr_in s_addr;
	struct sockaddr_in c_addr;

	int sockfd;
	socklen_t addr_len;
	int len;
	char buf[MAXBUF];
	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	if (sockfd == -1){
		perror("socket");
		exit(errno);
	}
	memset(&s_addr, 0, sizeof(s_addr));
	s_addr.sin_family = AF_INET;
	s_addr.sin_port = PORT;
	s_addr.sin_addr.s_addr = IP;

	if (-1 == (bind(sockfd, (struct sockaddr *) &s_addr, sizeof(s_addr)))) {
		perror("bind");
		exit(errno);
	} 
	addr_len = sizeof(c_addr);
	while (1) {
		len = recvfrom(sockfd, buf, sizeof(buf)-1, 0, (struct sockaddr *) &c_addr, &addr_len);
		if (len < 0) {
			perror("recvfrom");
			exit(errno);
		}
		buf[len] = '\0';
		printf("recive from %s:%d: %s\n",inet_ntoa(c_addr.sin_addr), ntohs(c_addr.sin_port), buf);
	}
	return 0;

}














